<template>
  <section class="page product-list-page">
    <h1 class="page-title">产品列表</h1>

    <!-- 筛选区 -->
    <el-card class="mb-3">
      <el-form :inline="true" label-width="80px" class="w-full">
        <el-form-item label="关键词">
          <el-input v-model="query.keyword" placeholder="请输入产品名关键词" clearable class="w-300" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="query.category" placeholder="全部" clearable class="w-200">
            <el-option label="全部" value="" />
            <el-option label="数码" value="digital" />
            <el-option label="图书" value="book" />
            <el-option label="玩具" value="toy" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区 -->
    <el-card>
      <el-table :data="list" stripe style="width: 100%" v-loading="loading" empty-text="暂无产品">
        <!-- 封面 -->
        <el-table-column label="封面" width="120" align="center">
          <template #default="{ row }">
            <el-image :src="row.cover" class="cover-img" fit="cover" @error="onImageError($event, row)" />
          </template>
        </el-table-column>

        <!-- 名称 -->
        <el-table-column label="产品名称" min-width="200">
          <template #default="{ row }">
            <el-text type="primary" class="fw-bold">{{ row.name }}</el-text>
          </template>
        </el-table-column>

        <!-- 分类 -->
        <el-table-column label="分类" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="categoryTagType(row.category)" size="small">{{ row.categoryName }}</el-tag>
          </template>
        </el-table-column>

        <!-- 简介 -->
        <el-table-column label="简介" min-width="220">
          <template #default="{ row }">
            <el-tooltip :content="row.description" placement="top" :disabled="!row.description">
              <span class="desc-ellipsis">{{ row.description || "—" }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 评分 -->
        <el-table-column label="评分" width="160" align="center">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled show-score score-template="{value}" />
          </template>
        </el-table-column>

        <!-- 库存 -->
        <el-table-column label="库存" width="120" align="center">
          <template #default="{ row }">
            <el-text :type="row.stock > 0 ? 'success' : 'danger'">{{ row.stock }}</el-text>
          </template>
        </el-table-column>

        <!-- 销量 -->
        <el-table-column label="销量" width="120" align="center">
          <template #default="{ row }">
            <el-text>{{ row.sales }}</el-text>
          </template>
        </el-table-column>

        <!-- 价格 -->
        <el-table-column label="价格" width="140" align="center">
          <template #default="{ row }">
            <el-text type="danger" class="fw-bold">¥ {{ row.price.toFixed(2) }}</el-text>
          </template>
        </el-table-column>

        <!-- 上架时间 -->
        <el-table-column label="上架时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="addToCart(row)">加入购物车</el-button>
            <el-button size="small" @click="viewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[6, 12, 24]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </section>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

interface Product {
  id: string;
  name: string;
  category: "digital" | "book" | "toy";
  categoryName: string;
  price: number;
  cover: string;
  // 新增字段
  description?: string;
  rating: number; // 0-5
  stock: number;
  sales: number;
  createdAt: string;
}

const query = reactive({ keyword: "", category: "" as "" | "digital" | "book" | "toy" });
const loading = ref(false);
const list = ref<Product[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(6);

const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)));
const categoryTagType = (c: Product["category"]) => (c === "digital" ? "success" : c === "book" ? "info" : "warning");

function formatDate(dateString: string) {
  return new Date(dateString).toLocaleString("zh-CN");
}

function mockFetchProducts(params: {
  keyword: string;
  category: string;
  page: number;
  pageSize: number;
}): Promise<{ list: Product[]; total: number }> {
  return new Promise((resolve) => {
    setTimeout(() => {
      const cats = ["digital", "book", "toy"] as const;
      const ALL: Product[] = Array.from({ length: 35 }).map((_, i) => {
        const c = cats[i % cats.length];
        const cn = c === "digital" ? "数码" : c === "book" ? "图书" : "玩具";
        return {
          id: `p_${i + 1}`,
          name: `示例产品 ${i + 1}`,
          category: c,
          categoryName: cn,
          price: Math.round(100 + Math.random() * 900),
          cover: `https://placehold.co/400x240?text=Product_${i + 1}`,
          description: `这是 ${cn} 类产品的示例简介，编号 ${i + 1}。`,
          rating: Math.round(Math.random() * 5),
          stock: Math.round(Math.random() * 200),
          sales: Math.round(Math.random() * 5000),
          createdAt: new Date(Date.now() - Math.random() * 1000 * 60 * 60 * 24 * 60).toISOString(), // 近两个月随机
        };
      });

      let filtered = ALL;
      if (params.keyword) filtered = filtered.filter((x) => x.name.includes(params.keyword));
      if (params.category) filtered = filtered.filter((x) => x.category === params.category);

      const start = (params.page - 1) * params.pageSize;
      resolve({ list: filtered.slice(start, start + params.pageSize), total: filtered.length });
    }, 600);
  });
}

async function fetchList() {
  loading.value = true;
  const res = await mockFetchProducts({
    keyword: query.keyword,
    category: query.category,
    page: page.value,
    pageSize: pageSize.value,
  });
  list.value = res.list;
  total.value = res.total;
  loading.value = false;
}

function search() {
  page.value = 1;
  fetchList();
}
function reset() {
  query.keyword = "";
  query.category = "";
  search();
}

function handleSizeChange(size: number) {
  pageSize.value = size;
  page.value = 1;
  fetchList();
}
function handleCurrentChange(p: number) {
  page.value = p;
  fetchList();
}

const COVER_FALLBACK = "https://placehold.co/400x240?text=No+Image";

function onImageError(_e: Event, row: Product) {
  row.cover = COVER_FALLBACK;
}

function addToCart(prod: Product) {
  ElMessage.success(`已加入购物车（模拟）：${prod.name}`);
}

function viewDetail(prod: Product) {
  ElMessageBox.alert(
    `名称：${prod.name}
分类：${prod.categoryName}
价格：¥ ${prod.price.toFixed(2)}
评分：${prod.rating}
库存：${prod.stock}
销量：${prod.sales}
上架时间：${formatDate(prod.createdAt)}
简介：${prod.description || "—"}`,
    "产品详情",
    { confirmButtonText: "好的" },
  );
}

onMounted(fetchList);
</script>

<style scoped lang="scss">
.page {
  padding: 16px;
}
.page-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
}
.cover-img {
  width: 96px;
  height: 64px;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.08);
}
.desc-ellipsis {
  display: inline-block;
  max-width: 320px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: bottom;
  color: #606266;
}
.pagination-section {
  display: flex;
  justify-content: flex-end;
  padding-top: 12px;
}
.w-300 {
  width: 300px;
}
.w-200 {
  width: 200px;
}
.fw-bold {
  font-weight: 600;
}
</style>
